﻿using Microsoft.AspNetCore.SignalR;

namespace Magic.System;

[Injection]
public class OnlineUserService : IOnlineUserService
{
    private readonly IHubContext<ChatHub, IChatHub> _hubContext;

    public OnlineUserService(IHubContext<ChatHub, IChatHub> hubContext)
    {
        _hubContext = hubContext;
    }
    /// <summary>
    /// 分页返回在线用户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<dynamic> GetOnlineUsersPage(BasePageInput page, OnlineUserQueryInput input)
    {
        var onlineUsers = await SugarContext.Instance.Queryable<SysUserOnline>()
            .ToPagedListAsync(page.Page, page.Limit);
        return onlineUsers;
    }
    /// <summary>
    /// 强制下线
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task ForceExist(OnlineUserInput input)
    {
        var onlineUser = await SugarContext.Instance.Queryable<SysUserOnline>().FirstAsync(p => p.ConnectionId == input.ConnectionId);
        _ = onlineUser ?? throw new ApiException("当前查询无数据");
        //在线踢人不能踢自己
        if (UserManager.UserId.ToString()==onlineUser.UserId)
            throw new ApiException("在线踢人功能不能踢自己");
        await _hubContext.Clients.Client(input.ConnectionId).ForceOffline("强制下线");
    }
}
